﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using CCWin;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using ERP_SaaS_WinForm.生产工单_报工_工序.Process;

namespace ERP_SaaS_WinForm.生产工单_报工_工序
{
    public partial class ProcessForm : CCSkinMain
    {
        // 分页参数
        private int currentPageIndex = 1;
        private int pageSize = 15;
        private int totalCount = 0;
        private int totalPage = 0;
        
        // 筛选参数 - 根据Swagger API文档，支持多个筛选条件
        private string filterDispatchCode = "";
        private string filterDispatchName = "";
        private string filterProductionOrdersCode = "";
        private string filterProductionOrdersName = "";
        private string filterReportingStaff = "";
        private string filterState = "";
        
        // 生产工单筛选参数
        private string ordersFilterCode = "";
        private string ordersFilterName = "";
        private string ordersFilterProductName = "";
        private string ordersFilterState = "";
        
        // 加载状态
        private bool isLoading = false;
        // 是否在工序面板中显示生产工单（否则显示工序）
        private bool showingOrders = false;

        // 生产工单界面控件（运行时创建，避免修改设计器）
        private Panel panelOrders;
        private Panel panelOrdersFilter;
        private Panel panelOrdersPaging;
        private DataGridView dgvOrders;
        private TextBox txtOrdersCode;
        private TextBox txtOrdersName;
        private TextBox txtOrdersProductName;
        private ComboBox cboOrdersState;
        private Button btnOrdersSearch;
        private Button btnOrdersReset;
        private Button btnOrdersSchedule;
        private Button btnOrdersFirst;
        private Button btnOrdersPrev;
        private Button btnOrdersNext;
        private Button btnOrdersLast;
        private ComboBox cboOrdersPageSize;
        private Label lblOrdersTotal;
        private Label lblOrdersPage;

        public ProcessForm()
        {
            InitializeComponent();
            InitializeReportControls();
        }

        private string GetProcessStateText(int state)
        {
            return state == 0 ? "启用" : "禁用";
        }

        // 追加一行工序信息（带颜色和对齐优化）
        private void AppendProcessRow(RichTextBox box, ProcessTable item)
        {
            if (box == null || item == null) return;
            var stateText = GetProcessStateText(item.State);

            // 行首颜色：启用绿色，禁用红色
            var color = item.State == 0 ? Color.FromArgb(34, 139, 34) : Color.FromArgb(178, 34, 34);
            int start = box.TextLength;
            string row = string.Format("{0,-8} {1,-12} {2,-15} {3,-8} {4,-20} {5,-20}\n",
                item.ProcessId,
                item.ProcessCode ?? "",
                item.ProcessName ?? "",
                stateText,
                (item.ProcessDescription ?? "").Length > 18 ? (item.ProcessDescription ?? "").Substring(0, 18) + ".." : (item.ProcessDescription ?? ""),
                (item.Remark ?? "").Length > 18 ? (item.Remark ?? "").Substring(0, 18) + ".." : (item.Remark ?? "")
            );
            box.AppendText(row);
            int end = box.TextLength;
            box.Select(start, end - start);
            box.SelectionColor = color;
            box.Select(end, 0);
        }



        private void ProcessForm_Load(object sender, EventArgs e)
        {
            // 默认显示工序面板
            ShowProcessPanel();
            _ = LoadProcessesAsync();
            
            // 测试操作列显示
            Console.WriteLine("ProcessForm加载完成，开始测试操作列...");
            if (dgvOrders != null)
            {
                Console.WriteLine($"dgvOrders列数: {dgvOrders.Columns.Count}");
                EnsureOrdersActionColumn();
                Console.WriteLine($"确保操作列后，列数: {dgvOrders.Columns.Count}");
            }
        }

        private void InitializeReportControls()
        {
            // 设置默认页大小
            cboReportPageSize.SelectedIndex = 0;
            pageSize = 15; // 确保pageSize变量被正确初始化
            
            // 设置筛选框的提示文本
            txtDispatchCode.Text = "输入派工编号";
            txtDispatchCode.ForeColor = Color.Gray;
            
            txtDispatchName.Text = "输入派工名称";
            txtDispatchName.ForeColor = Color.Gray;
            
            txtProductionOrdersCode.Text = "输入工单编号";
            txtProductionOrdersCode.ForeColor = Color.Gray;
            
            txtProductionOrdersName.Text = "输入工单名称";
            txtProductionOrdersName.ForeColor = Color.Gray;
            
            txtReportingStaff.Text = "输入报工人员";
            txtReportingStaff.ForeColor = Color.Gray;
            
            // 初始化状态下拉框
            cboState.Items.Clear();
            cboState.Items.Add("请选择");
            cboState.Items.Add("未质检");
            cboState.Items.Add("已质检");
            cboState.SelectedIndex = 0;
            
            // 绑定事件
            btnReportSearch.Click += BtnReportSearch_Click;
            btnReportReset.Click += BtnReportReset_Click;
            btnReportFirst.Click += BtnReportFirst_Click;
            btnReportPrev.Click += BtnReportPrev_Click;
            btnReportNext.Click += BtnReportNext_Click;
            btnReportLast.Click += BtnReportLast_Click;
            cboReportPageSize.SelectedIndexChanged += CboReportPageSize_SelectedIndexChanged;
            btnReportBatchDelete.Click += BtnReportBatchDelete_Click;
            btnReportExport.Click += BtnReportExport_Click;
            
            // 绑定筛选框的事件
            txtDispatchCode.KeyPress += TxtDispatchCode_KeyPress;
            txtDispatchCode.Enter += TxtDispatchCode_Enter;
            txtDispatchCode.Leave += TxtDispatchCode_Leave;
            
            txtDispatchName.KeyPress += TxtDispatchName_KeyPress;
            txtDispatchName.Enter += TxtDispatchName_Enter;
            txtDispatchName.Leave += TxtDispatchName_Leave;
            
            txtProductionOrdersCode.KeyPress += TxtProductionOrdersCode_KeyPress;
            txtProductionOrdersCode.Enter += TxtProductionOrdersCode_Enter;
            txtProductionOrdersCode.Leave += TxtProductionOrdersCode_Leave;
            
            txtProductionOrdersName.KeyPress += TxtProductionOrdersName_KeyPress;
            txtProductionOrdersName.Enter += TxtProductionOrdersName_Enter;
            txtProductionOrdersName.Leave += TxtProductionOrdersName_Leave;
            
            txtReportingStaff.KeyPress += TxtReportingStaff_KeyPress;
            txtReportingStaff.Enter += TxtReportingStaff_Enter;
            txtReportingStaff.Leave += TxtReportingStaff_Leave;
            
            cboState.SelectedIndexChanged += CboState_SelectedIndexChanged;
            
            // 绑定菜单事件
            menuProcess.Click += MenuProcess_Click;
            menuReport.Click += MenuReport_Click;
            menuRefresh.Click += MenuRefresh_Click;
            生产工单ToolStripMenuItem.Click += 生产工单ToolStripMenuItem_Click;
            
            // 设置窗体标题
            this.Text = "生产工单管理系统";
            
            // 设置RichTextBox右键菜单
            SetupRichTextBoxContextMenu();

            // 初始化生产工单界面
            InitializeOrdersControls();
        }

        private void InitializeOrdersControls()
        {
            panelOrders = new Panel { Dock = DockStyle.Fill, Visible = false };
            panelOrdersFilter = new Panel { Dock = DockStyle.Top, Height = 50 };
            panelOrdersPaging = new Panel { Dock = DockStyle.Bottom, Height = 50 };
            dgvOrders = new DataGridView
            {
                Dock = DockStyle.Fill,
                AllowUserToAddRows = false,
                AllowUserToDeleteRows = false,
                ReadOnly = true,
                SelectionMode = DataGridViewSelectionMode.FullRowSelect,
                BackgroundColor = Color.White,
                RowHeadersVisible = false,
                ScrollBars = ScrollBars.Both
            };

            // 过滤区控件
            txtOrdersCode = new TextBox { Width = 110, Text = "输入工单编号", Location = new Point(90, 12) };
            var lblOC = new Label { Text = "工单编号:", Location = new Point(10, 15), AutoSize = true };
            txtOrdersName = new TextBox { Width = 110, Text = "输入工单名称", Location = new Point(300, 12) };
            var lblON = new Label { Text = "工单名称:", Location = new Point(220, 15), AutoSize = true };
            txtOrdersProductName = new TextBox { Width = 110, Text = "输入产品名称", Location = new Point(510, 12) };
            var lblPN = new Label { Text = "产品名称:", Location = new Point(430, 15), AutoSize = true };
            cboOrdersState = new ComboBox { DropDownStyle = ComboBoxStyle.DropDownList, Location = new Point(700, 12), Width = 100 };
            var lblOS = new Label { Text = "状态:", Location = new Point(650, 15), AutoSize = true };
            cboOrdersState.Items.AddRange(new object[] { "请选择", "待排产", "未开始", "进行中", "已完成", "已暂停", "已关闭" });
            cboOrdersState.SelectedIndex = 0;
            btnOrdersSearch = new Button { Text = "搜索", Location = new Point(820, 10), Width = 60, Height = 30 };
            btnOrdersReset = new Button { Text = "重置", Location = new Point(890, 10), Width = 60, Height = 30 };
            btnOrdersSchedule = new Button { Text = "排产", Location = new Point(960, 10), Width = 60, Height = 30 };

            btnOrdersSearch.Click += (s, e) =>
            {
                if (isLoading) return;
                ordersFilterCode = GetFilterValue(txtOrdersCode, "输入工单编号");
                ordersFilterName = GetFilterValue(txtOrdersName, "输入工单名称");
                ordersFilterProductName = GetFilterValue(txtOrdersProductName, "输入产品名称");
                ordersFilterState = GetOrdersStateFilterValue();
                currentPageIndex = 1;
                _ = LoadProductionOrdersAsync();
            };

            btnOrdersReset.Click += (s, e) =>
            {
                if (isLoading) return;
                txtOrdersCode.Text = "输入工单编号";
                txtOrdersName.Text = "输入工单名称";
                txtOrdersProductName.Text = "输入产品名称";
                cboOrdersState.SelectedIndex = 0;
                ordersFilterCode = ordersFilterName = ordersFilterProductName = ordersFilterState = "";
                currentPageIndex = 1;
                _ = LoadProductionOrdersAsync();
            };

            panelOrdersFilter.Controls.AddRange(new Control[] { lblOC, txtOrdersCode, lblON, txtOrdersName, lblPN, txtOrdersProductName, lblOS, cboOrdersState, btnOrdersSearch, btnOrdersReset, btnOrdersSchedule });

            // 占位符与回车搜索
            SetupOrdersPlaceholder(txtOrdersCode, "输入工单编号");
            SetupOrdersPlaceholder(txtOrdersName, "输入工单名称");
            SetupOrdersPlaceholder(txtOrdersProductName, "输入产品名称");

            // 分页区
            lblOrdersTotal = new Label { Location = new Point(10, 15), AutoSize = true, Text = "共0条" };
            lblOrdersPage = new Label { Location = new Point(80, 15), AutoSize = true, Text = "第1页/共1页" };
            btnOrdersFirst = new Button { Text = "首页", Location = new Point(180, 10), Width = 50, Height = 30 };
            btnOrdersPrev = new Button { Text = "上页", Location = new Point(240, 10), Width = 50, Height = 30 };
            btnOrdersNext = new Button { Text = "下页", Location = new Point(300, 10), Width = 50, Height = 30 };
            btnOrdersLast = new Button { Text = "末页", Location = new Point(360, 10), Width = 50, Height = 30 };
            cboOrdersPageSize = new ComboBox { DropDownStyle = ComboBoxStyle.DropDownList, Location = new Point(420, 12), Width = 60 };
            cboOrdersPageSize.Items.AddRange(new object[] { "15", "30", "50", "100" });
            cboOrdersPageSize.SelectedIndex = 0;

            btnOrdersFirst.Click += (s, e) => { if (isLoading) return; currentPageIndex = 1; _ = LoadProductionOrdersAsync(); };
            btnOrdersPrev.Click += (s, e) => { if (isLoading) return; if (currentPageIndex > 1) { currentPageIndex--; _ = LoadProductionOrdersAsync(); } };
            btnOrdersNext.Click += (s, e) => { if (isLoading) return; if (currentPageIndex < totalPage) { currentPageIndex++; _ = LoadProductionOrdersAsync(); } };
            btnOrdersLast.Click += (s, e) => { if (isLoading) return; currentPageIndex = totalPage; _ = LoadProductionOrdersAsync(); };
            cboOrdersPageSize.SelectedIndexChanged += (s, e) => { if (isLoading) return; pageSize = int.Parse(cboOrdersPageSize.SelectedItem.ToString()); currentPageIndex = 1; _ = LoadProductionOrdersAsync(); };

            panelOrdersPaging.Controls.AddRange(new Control[] { lblOrdersTotal, lblOrdersPage, btnOrdersFirst, btnOrdersPrev, btnOrdersNext, btnOrdersLast, cboOrdersPageSize });

            panelOrders.Controls.Add(dgvOrders);
            panelOrders.Controls.Add(panelOrdersFilter);
            panelOrders.Controls.Add(panelOrdersPaging);

            // 插入到主容器
            panelMain.Controls.Add(panelOrders);

            btnOrdersSchedule.Click += (s, e) =>
            {
                if (isLoading) return;
                if (dgvOrders?.DataSource is List<ProductionOrders> orders && dgvOrders.CurrentRow != null)
                {
                    var current = dgvOrders.CurrentRow.DataBoundItem as ProductionOrders;
                    using (var dlg = new ScheduleForm(current))
                    {
                        if (dlg.ShowDialog(this) == DialogResult.OK)
                        {
                            // 排产成功后，立即刷新数据以显示状态变化
                            _ = LoadProductionOrdersAsync();
                            // 强制刷新当前行的显示
                            RefreshOrdersDisplay();
                        }
                    }
                }
                else
                {
                    MessageBox.Show("请先选择一条生产工单", "排产", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            };
        }

        // 派工编号筛选框事件处理
        private void TxtDispatchCode_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Enter)
            {
                e.Handled = true;
                _ = LoadReportsAsync();
            }
        }

        private void TxtDispatchCode_Enter(object sender, EventArgs e)
        {
            if (txtDispatchCode.Text == "输入派工编号")
            {
                txtDispatchCode.Text = "";
                txtDispatchCode.ForeColor = Color.Black;
            }
        }

        private void TxtDispatchCode_Leave(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(txtDispatchCode.Text))
            {
                txtDispatchCode.Text = "输入派工编号";
                txtDispatchCode.ForeColor = Color.Gray;
            }
        }

        // 工单编号筛选框事件处理
        private void TxtProductionOrdersCode_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Enter)
            {
                e.Handled = true;
                _ = LoadReportsAsync();
            }
        }

        private void TxtProductionOrdersCode_Enter(object sender, EventArgs e)
        {
            if (txtProductionOrdersCode.Text == "输入工单编号")
            {
                txtProductionOrdersCode.Text = "";
                txtProductionOrdersCode.ForeColor = Color.Black;
            }
        }

        private void TxtProductionOrdersCode_Leave(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(txtProductionOrdersCode.Text))
            {
                txtProductionOrdersCode.Text = "输入工单编号";
                txtProductionOrdersCode.ForeColor = Color.Gray;
            }
        }

        // 派工名称筛选框事件处理
        private void TxtDispatchName_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Enter)
            {
                e.Handled = true;
                _ = LoadReportsAsync();
            }
        }

        private void TxtDispatchName_Enter(object sender, EventArgs e)
        {
            if (txtDispatchName.Text == "输入派工名称")
            {
                txtDispatchName.Text = "";
                txtDispatchName.ForeColor = Color.Black;
            }
        }

        private void TxtDispatchName_Leave(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(txtDispatchName.Text))
            {
                txtDispatchName.Text = "输入派工名称";
                txtDispatchName.ForeColor = Color.Gray;
            }
        }

        // 工单名称筛选框事件处理
        private void TxtProductionOrdersName_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Enter)
            {
                e.Handled = true;
                _ = LoadReportsAsync();
            }
        }

        private void TxtProductionOrdersName_Enter(object sender, EventArgs e)
        {
            if (txtProductionOrdersName.Text == "输入工单名称")
            {
                txtProductionOrdersName.Text = "";
                txtProductionOrdersName.ForeColor = Color.Black;
            }
        }

        private void TxtProductionOrdersName_Leave(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(txtProductionOrdersName.Text))
            {
                txtProductionOrdersName.Text = "输入工单名称";
                txtProductionOrdersName.ForeColor = Color.Gray;
            }
        }

        // 报工人员筛选框事件处理
        private void TxtReportingStaff_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Enter)
            {
                e.Handled = true;
                _ = LoadReportsAsync();
            }
        }

        private void TxtReportingStaff_Enter(object sender, EventArgs e)
        {
            if (txtReportingStaff.Text == "输入报工人员")
            {
                txtReportingStaff.Text = "";
                txtReportingStaff.ForeColor = Color.Black;
            }
        }

        private void TxtReportingStaff_Leave(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(txtReportingStaff.Text))
            {
                txtReportingStaff.Text = "输入报工人员";
                txtReportingStaff.ForeColor = Color.Gray;
            }
        }

        // 状态下拉框事件处理
        private void CboState_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (isLoading) return;
            // 当状态选择改变时，自动触发搜索
            _ = LoadReportsAsync();
        }

        // 数据网格单元格格式化事件处理
        private void DgvReport_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (e.ColumnIndex >= 0 && e.RowIndex >= 0)
            {
                var column = dgvReport.Columns[e.ColumnIndex];
                if (column.Name == nameof(ReportTable.State))
                {
                    if (e.Value != null && int.TryParse(e.Value.ToString(), out int stateValue))
                    {
                        switch (stateValue)
                        {
                            case 0:
                                e.Value = "未质检";
                                break;
                            case 1:
                                e.Value = "已质检";
                                break;
                            default:
                                e.Value = "未知状态";
                                break;
                        }
                        e.FormattingApplied = true;
                    }
                }
            }
        }

        private void DgvOrders_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (e.ColumnIndex >= 0 && e.RowIndex >= 0)
            {
                var grid = sender as DataGridView;
                var column = grid.Columns[e.ColumnIndex];
                if (column.Name == nameof(ProductionOrders.State))
                {
                    if (e.Value != null && int.TryParse(e.Value.ToString(), out int stateValue))
                    {
                        switch (stateValue)
                        {
                            case 0: e.Value = "待排产"; break;
                            case 1: e.Value = "未开始"; break;
                            case 2: e.Value = "进行中"; break;
                            case 3: e.Value = "已完成"; break;
                            case 4: e.Value = "已暂停"; break;
                            case 5: e.Value = "已关闭"; break;
                            default: e.Value = "未知"; break;
                        }
                        e.FormattingApplied = true;
                    }
                }
            }
        }

        // 操作列格式化：根据工单状态动态显示按钮文本和样式
        private void DgvOrdersAction_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (e.ColumnIndex >= 0 && e.RowIndex >= 0)
            {
                var grid = sender as DataGridView;
                var column = grid.Columns[e.ColumnIndex];
                if (column.Name == "colSchedule")
                {
                    if (grid.Rows[e.RowIndex].DataBoundItem is ProductionOrders order)
                    {
                        // 动态设置按钮文本
                        string buttonText = order.State == 0 ? "排产" : "查看";
                        e.Value = buttonText;
                        e.FormattingApplied = true;
                        
                        // 设置按钮样式
                        var row = grid.Rows[e.RowIndex];
                        if (order.State == 0)
                        {
                            // 待排产状态：蓝色按钮
                            row.Cells[e.ColumnIndex].Style.BackColor = Color.LightBlue;
                            row.Cells[e.ColumnIndex].Style.ForeColor = Color.Black;
                        }
                        else
                        {
                            // 其他状态：灰色按钮
                            row.Cells[e.ColumnIndex].Style.BackColor = Color.LightGray;
                            row.Cells[e.ColumnIndex].Style.ForeColor = Color.Black;
                        }
                    }
                }
            }
        }

        private void CboReportPageSize_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (isLoading) return;
            if (cboReportPageSize.SelectedItem != null)
            {
                pageSize = int.Parse(cboReportPageSize.SelectedItem.ToString());
                currentPageIndex = 1;
                _ = LoadReportsAsync();
            }
        }

        private void BtnReportLast_Click(object sender, EventArgs e)
        {
            if (isLoading) return;
            currentPageIndex = totalPage;
            _ = LoadReportsAsync();
        }

        private void BtnReportNext_Click(object sender, EventArgs e)
        {
            if (isLoading) return;
            Console.WriteLine($"点击下页按钮，当前页: {currentPageIndex}, 总页数: {totalPage}");
            if (currentPageIndex < totalPage)
            {
                currentPageIndex++;
                Console.WriteLine($"下页按钮: 当前页设置为: {currentPageIndex}");
                _ = LoadReportsAsync();
            }
            else
            {
                Console.WriteLine($"无法点击下页，当前页: {currentPageIndex}, 总页数: {totalPage}");
                MessageBox.Show($"已经是最后一页了！", "分页提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void BtnReportPrev_Click(object sender, EventArgs e)
        {
            if (isLoading) return;
            Console.WriteLine($"点击上页按钮，当前页: {currentPageIndex}");
            if (currentPageIndex > 1)
            {
                currentPageIndex--;
                Console.WriteLine($"上页按钮: 当前页设置为: {currentPageIndex}");
                _ = LoadReportsAsync();
            }
            else
            {
                Console.WriteLine($"无法点击上页，当前页: {currentPageIndex}");
                MessageBox.Show($"已经是第一页了！", "分页提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void BtnReportFirst_Click(object sender, EventArgs e)
        {
            if (isLoading) return;
            currentPageIndex = 1;
            Console.WriteLine($"点击首页按钮，当前页设置为: {currentPageIndex}");
            _ = LoadReportsAsync();
        }

        private void BtnReportReset_Click(object sender, EventArgs e)
        {
            if (isLoading) return;
            
            // 重置所有筛选框
            txtDispatchCode.Text = "输入派工编号";
            txtDispatchCode.ForeColor = Color.Gray;
            
            txtDispatchName.Text = "输入派工名称";
            txtDispatchName.ForeColor = Color.Gray;
            
            txtProductionOrdersCode.Text = "输入工单编号";
            txtProductionOrdersCode.ForeColor = Color.Gray;
            
            txtProductionOrdersName.Text = "输入工单名称";
            txtProductionOrdersName.ForeColor = Color.Gray;
            
            txtReportingStaff.Text = "输入报工人员";
            txtReportingStaff.ForeColor = Color.Gray;
            
            cboState.SelectedIndex = 0;
            
            // 清空筛选条件
            filterDispatchCode = "";
            filterDispatchName = "";
            filterProductionOrdersCode = "";
            filterProductionOrdersName = "";
            filterReportingStaff = "";
            filterState = "";
            
            currentPageIndex = 1;
            _ = LoadReportsAsync();
        }

        private async void BtnReportBatchDelete_Click(object sender, EventArgs e)
        {
            if (isLoading) return;
            if (dgvReport.SelectedRows == null || dgvReport.SelectedRows.Count == 0)
            {
                MessageBox.Show("请先选择要删除的报工记录（可多选）", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            // 收集所选行的 ReportId（注意：接口参数名为 ReportIds，可重复传递）
            var selectedIds = new List<int>();
            foreach (DataGridViewRow row in dgvReport.SelectedRows)
            {
                if (row.DataBoundItem is ReportTable report)
                {
                    selectedIds.Add(report.ReportId);
                }
            }

            if (selectedIds.Count == 0)
            {
                MessageBox.Show("未找到可删除的记录主键", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            // 友好提示：展示部分ID示例并标注不可恢复
            var previewIds = string.Join(", ", selectedIds.Take(10));
            var moreSuffix = selectedIds.Count > 10 ? " 等" : string.Empty;
            var confirmText = $"确认删除选中的 {selectedIds.Count} 条报工记录吗？\n示例ID: {previewIds}{moreSuffix}\n此操作不可恢复。";
            var confirm = MessageBox.Show(confirmText, "确认删除", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
            if (confirm != DialogResult.Yes) return;

            try
            {
                using (var httpClient = new HttpClient())
                {
                    httpClient.Timeout = TimeSpan.FromSeconds(15);
                    httpClient.DefaultRequestHeaders.Accept.Clear();
                    httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                    // 构造批量删除的查询字符串：/api/Report/DelReportCommand?ReportIds=0&ReportIds=1
                    var baseUrl = "http://localhost:5257/api/Report/DelReportCommand";
                    var queryParts = new List<string>();
                    foreach (var id in selectedIds)
                    {
                        queryParts.Add($"ReportIds={Uri.EscapeDataString(id.ToString())}");
                    }
                    var requestUrl = baseUrl + "?" + string.Join("&", queryParts);

                    Console.WriteLine($"批量删除请求URL: {requestUrl}");
                    // 保持在UI上下文，避免跨线程更新控件
                    var response = await httpClient.GetAsync(requestUrl);
                    response.EnsureSuccessStatusCode();

                    var json = await response.Content.ReadAsStringAsync();
                    var apiResponse = JsonConvert.DeserializeObject<SimpleApiResponse<int>>(json);

                    if (apiResponse != null && apiResponse.code == 200)
                    {
                        MessageBox.Show(apiResponse.message ?? "批量删除成功", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        // 先本地移除以获得即时视觉反馈（确保在UI线程）
                        void RemoveLocally()
                        {
                            if (dgvReport.DataSource is List<ReportTable> currentItems)
                            {
                                var afterItems = currentItems.Where(x => !selectedIds.Contains(x.ReportId)).ToList();
                                dgvReport.DataSource = afterItems;
                            }
                        }
                        if (dgvReport.InvokeRequired) dgvReport.Invoke(new Action(RemoveLocally)); else RemoveLocally();
                        // 然后从服务器刷新：优先尝试留在当前页，若当前页超出范围则跳转到最后一页
                        var pageBefore = currentPageIndex;
                        if (InvokeRequired)
                        {
                            await Task.Run(() => { }); // no-op占位，保持语义
                            Invoke(new Action(async () =>
                            {
                                await LoadReportsAsync();
                                if (totalPage > 0 && pageBefore > totalPage)
                                {
                                    currentPageIndex = totalPage;
                                    await LoadReportsAsync();
                                }
                            }));
                        }
                        else
                        {
                            await LoadReportsAsync();
                            if (totalPage > 0 && pageBefore > totalPage)
                            {
                                currentPageIndex = totalPage;
                                await LoadReportsAsync();
                            }
                        }
                    }
                    else
                    {
                        var msg = apiResponse?.message ?? "批量删除失败";
                        MessageBox.Show(msg, "失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"批量删除失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void BtnReportExport_Click(object sender, EventArgs e)
        {
            if (dgvReport.DataSource is List<ReportTable> items && items.Count > 0)
            {
                using (var sfd = new SaveFileDialog())
                {
                    sfd.Title = "导出报工数据";
                    sfd.Filter = "CSV 文件 (*.csv)|*.csv";
                    sfd.FileName = $"报工导出_{DateTime.Now:yyyyMMdd_HHmmss}.csv";
                    if (sfd.ShowDialog() == DialogResult.OK)
                    {
                        try
                        {
                            var sb = new StringBuilder();
                            sb.AppendLine("ReportId,DispatchCode,DispatchName,ProductionOrdersCode,ProductionOrdersName,SiteName,CraftName,ProcessName,ProcessCode,TeamName,Leader,ReportingStaff,ReportingNumber,ReportingTime,QualityInspectionTime,Qualified,NotQualified,Rate,State");
                            foreach (var r in items)
                            {
                                string Escape(string v) => string.IsNullOrEmpty(v) ? "" : (v.Contains(",") || v.Contains("\"") ? $"\"{v.Replace("\"","\"\"")}\"" : v);
                                sb.AppendLine(string.Join(",", new string[]
                                {
                                    r.ReportId.ToString(),
                                    Escape(r.DispatchCode),
                                    Escape(r.DispatchName),
                                    Escape(r.ProductionOrdersCode),
                                    Escape(r.ProductionOrdersName),
                                    Escape(r.SiteName),
                                    Escape(r.CraftName),
                                    Escape(r.ProcessName),
                                    Escape(r.ProcessCode),
                                    Escape(r.TeamName),
                                    Escape(r.Leader),
                                    Escape(r.ReportingStaff),
                                    r.ReportingNumber.ToString(),
                                    r.ReportingTime.ToString("yyyy-MM-dd HH:mm:ss"),
                                    r.QualityInspectionTime.ToString("yyyy-MM-dd HH:mm:ss"),
                                    r.Qualified.ToString(),
                                    r.NotQualified.ToString(),
                                    r.Rate.ToString(),
                                    r.State.ToString()
                                }));
                            }
                            System.IO.File.WriteAllText(sfd.FileName, sb.ToString(), Encoding.UTF8);
                            MessageBox.Show("导出成功", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show($"导出失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                }
            }
            else
            {
                MessageBox.Show("当前没有可导出的数据", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void BtnReportSearch_Click(object sender, EventArgs e)
        {
            if (isLoading) return;
            
            // 获取所有筛选框的原始值
            var rawDispatchCode = txtDispatchCode.Text.Trim();
            var rawDispatchName = txtDispatchName.Text.Trim();
            var rawProductionOrdersCode = txtProductionOrdersCode.Text.Trim();
            var rawProductionOrdersName = txtProductionOrdersName.Text.Trim();
            var rawReportingStaff = txtReportingStaff.Text.Trim();
            var rawState = cboState.Text.Trim();
            
            var rawStateDisplay = cboState.SelectedIndex == 0 ? "请选择" : cboState.Text;
            Console.WriteLine($"原始输入值: 派工编号='{rawDispatchCode}', 派工名称='{rawDispatchName}', 工单编号='{rawProductionOrdersCode}', 工单名称='{rawProductionOrdersName}', 报工人员='{rawReportingStaff}', 状态='{rawStateDisplay}'");
            
            // 获取所有筛选框的值
            filterDispatchCode = GetFilterValue(txtDispatchCode, "输入派工编号");
            filterDispatchName = GetFilterValue(txtDispatchName, "输入派工名称");
            filterProductionOrdersCode = GetFilterValue(txtProductionOrdersCode, "输入工单编号");
            filterProductionOrdersName = GetFilterValue(txtProductionOrdersName, "输入工单名称");
            filterReportingStaff = GetFilterValue(txtReportingStaff, "输入报工人员");
            filterState = GetStateFilterValue();
            
            // 添加调试信息
            var filterStateDisplay = GetStateDisplayText(filterState);
            Console.WriteLine($"处理后的筛选条件: 派工编号='{filterDispatchCode}', 派工名称='{filterDispatchName}', 工单编号='{filterProductionOrdersCode}', 工单名称='{filterProductionOrdersName}', 报工人员='{filterReportingStaff}', 状态='{filterStateDisplay}'");
            Console.WriteLine($"筛选条件是否为空: 派工编号={string.IsNullOrEmpty(filterDispatchCode)}, 派工名称={string.IsNullOrEmpty(filterDispatchName)}, 工单编号={string.IsNullOrEmpty(filterProductionOrdersCode)}, 工单名称={string.IsNullOrEmpty(filterProductionOrdersName)}, 报工人员={string.IsNullOrEmpty(filterReportingStaff)}, 状态={string.IsNullOrEmpty(filterState)}");
            
            var stateDisplay = GetStateDisplayText(filterState);
            MessageBox.Show($"正在搜索:\n派工编号: {filterDispatchCode}\n派工名称: {filterDispatchName}\n工单编号: {filterProductionOrdersCode}\n工单名称: {filterProductionOrdersName}\n报工人员: {filterReportingStaff}\n状态: {stateDisplay}", "搜索信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
            
            currentPageIndex = 1;
            _ = LoadReportsAsync();
        }
        
        private string GetFilterValue(TextBox textBox, string placeholder)
        {
            var text = textBox.Text.Trim();
            // 修复筛选值获取逻辑：只有当文本完全等于占位符时才返回空字符串
            // 如果用户输入了实际内容（即使是"0545"这样的值），应该保留
            if (text == placeholder || string.IsNullOrWhiteSpace(text))
            {
                return "";
            }
            return text;
        }

        private string GetStateFilterValue()
        {
            if (cboState.SelectedIndex == 0) // "请选择"
            {
                return "";
            }
            else if (cboState.SelectedIndex == 1) // "未质检"
            {
                return "0";
            }
            else if (cboState.SelectedIndex == 2) // "已质检"
            {
                return "1";
            }
            return "";
        }

        private string GetStateDisplayText(string stateValue)
        {
            if (string.IsNullOrEmpty(stateValue))
            {
                return "全部";
            }
            else if (stateValue == "0")
            {
                return "未质检";
            }
            else if (stateValue == "1")
            {
                return "已质检";
            }
            return stateValue;
        }

        private void MenuProcess_Click(object sender, EventArgs e)
        {
            if (isLoading) return;
            showingOrders = false;
            ShowProcessPanel();
            _ = LoadProcessesAsync();
        }

        private void MenuReport_Click(object sender, EventArgs e)
        {
            if (isLoading) return;
            ShowReportPanel();
            _ = LoadReportsAsync();
        }

        private void MenuRefresh_Click(object sender, EventArgs e)
        {
            if (isLoading) return;
            if (showingOrders)
            {
                _ = LoadProductionOrdersAsync();
            }
            else if (panelProcess.Visible)
            {
                _ = LoadProcessesAsync();
            }
            else
            {
                _ = LoadReportsAsync();
            }
        }

        private void 生产工单ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (isLoading) return;
            showingOrders = true;
            ShowOrdersPanel();
            _ = LoadProductionOrdersAsync();
        }

        private void ShowProcessPanel()
        {
            panelProcess.Visible = true;
            panelReport.Visible = false;
            if (panelOrders != null) panelOrders.Visible = false;
        }

        private void ShowReportPanel()
        {
            panelProcess.Visible = false;
            panelReport.Visible = true;
            if (panelOrders != null) panelOrders.Visible = false;
        }

        private void ShowOrdersPanel()
        {
            panelProcess.Visible = false;
            panelReport.Visible = false;
            if (panelOrders != null) panelOrders.Visible = true;
        }

        private void SetupRichTextBoxContextMenu()
        {
            var contextMenu = new ContextMenuStrip();
            
            var copyItem = new ToolStripMenuItem("复制");
            copyItem.Click += (sender, e) => rtbProcess.Copy();
            
            var selectAllItem = new ToolStripMenuItem("全选");
            selectAllItem.Click += (sender, e) => rtbProcess.SelectAll();
            
            var clearItem = new ToolStripMenuItem("清空");
            clearItem.Click += (sender, e) => rtbProcess.Clear();
            
            var refreshItem = new ToolStripMenuItem("刷新数据");
            refreshItem.Click += (sender, e) => _ = LoadProcessesAsync();
            
            contextMenu.Items.AddRange(new ToolStripItem[]
            {
                copyItem,
                selectAllItem,
                new ToolStripSeparator(),
                clearItem,
                refreshItem
            });
            
            rtbProcess.ContextMenuStrip = contextMenu;
            
            // 设置RichTextBox样式
            rtbProcess.BackColor = Color.White;
            rtbProcess.BorderStyle = BorderStyle.None;
            rtbProcess.Font = new Font("Consolas", 9, FontStyle.Regular);
            rtbProcess.ReadOnly = true;
            rtbProcess.WordWrap = false;
            rtbProcess.ScrollBars = RichTextBoxScrollBars.Both;
            rtbProcess.KeyDown += RtbProcess_KeyDown;
        }

        private void RtbProcess_KeyDown(object sender, KeyEventArgs e)
        {
            if (!panelProcess.Visible || !showingOrders || isLoading) return;
            if (e.KeyCode == Keys.Right || e.KeyCode == Keys.PageDown)
            {
                if (currentPageIndex < totalPage)
                {
                    currentPageIndex++;
                    _ = LoadProductionOrdersAsync();
                }
                e.Handled = true;
            }
            else if (e.KeyCode == Keys.Left || e.KeyCode == Keys.PageUp)
            {
                if (currentPageIndex > 1)
                {
                    currentPageIndex--;
                    _ = LoadProductionOrdersAsync();
                }
                e.Handled = true;
            }
            else if (e.KeyCode == Keys.Home)
            {
                if (currentPageIndex != 1)
                {
                    currentPageIndex = 1;
                    _ = LoadProductionOrdersAsync();
                }
                e.Handled = true;
            }
            else if (e.KeyCode == Keys.End)
            {
                if (currentPageIndex != totalPage && totalPage > 0)
                {
                    currentPageIndex = totalPage;
                    _ = LoadProductionOrdersAsync();
                }
                e.Handled = true;
            }
        }

        private void SetupOrdersPlaceholder(TextBox textBox, string placeholder)
        {
            textBox.ForeColor = Color.Gray;
            textBox.Enter += (s, e) =>
            {
                if (textBox.Text == placeholder)
                {
                    textBox.Text = "";
                    textBox.ForeColor = Color.Black;
                }
            };
            textBox.Leave += (s, e) =>
            {
                if (string.IsNullOrWhiteSpace(textBox.Text))
                {
                    textBox.Text = placeholder;
                    textBox.ForeColor = Color.Gray;
                }
            };
            textBox.KeyPress += (s, e) =>
            {
                if (e.KeyChar == (char)Keys.Enter)
                {
                    e.Handled = true;
                    btnOrdersSearch.PerformClick();
                }
            };
        }

        private void UpdatePagingInfo()
        {
            if (InvokeRequired)
            {
                Invoke(new Action(UpdatePagingInfo));
                return;
            }

            lblReportTotal.Text = $"共{totalCount}条";
            lblReportPage.Text = $"第{currentPageIndex}页/共{totalPage}页";

            // 更新按钮状态 - 根据Swagger API文档修复分页逻辑
            bool hasData = totalCount > 0;
            bool canGoFirst = currentPageIndex > 1;
            bool canGoPrev = currentPageIndex > 1;
            bool canGoNext = hasData && currentPageIndex < totalPage;
            bool canGoLast = hasData && currentPageIndex < totalPage;
            
            btnReportFirst.Enabled = canGoFirst && !isLoading;
            btnReportPrev.Enabled = canGoPrev && !isLoading;
            btnReportNext.Enabled = canGoNext && !isLoading;
            btnReportLast.Enabled = canGoLast && !isLoading;
            
            // 添加调试信息
            Console.WriteLine($"分页信息更新: 总数={totalCount}, 当前页={currentPageIndex}, 总页数={totalPage}");
            Console.WriteLine($"按钮状态: 首页={canGoFirst}, 上页={canGoPrev}, 下页={canGoNext}, 末页={canGoLast}");
            Console.WriteLine($"分页按钮启用状态: 首页={btnReportFirst.Enabled}, 上页={btnReportPrev.Enabled}, 下页={btnReportNext.Enabled}, 末页={btnReportLast.Enabled}");
        }

        private void UpdateLoadingState(bool loading)
        {
            if (InvokeRequired)
            {
                Invoke(new Action<bool>(UpdateLoadingState), loading);
                return;
            }

            // 更新控件状态
            btnReportSearch.Enabled = !loading;
            btnReportReset.Enabled = !loading;
            btnReportBatchDelete.Enabled = !loading;
            cboReportPageSize.Enabled = !loading;
            txtDispatchCode.Enabled = !loading;
            txtDispatchName.Enabled = !loading;
            txtProductionOrdersCode.Enabled = !loading;
            txtProductionOrdersName.Enabled = !loading;
            txtReportingStaff.Enabled = !loading;
            cboState.Enabled = !loading;
            
            // 更新菜单状态
            menuProcess.Enabled = !loading;
            menuReport.Enabled = !loading;
            menuRefresh.Enabled = !loading;
            // 订单过滤控件
            if (panelOrders != null)
            {
                if (btnOrdersSearch != null) btnOrdersSearch.Enabled = !loading;
                if (btnOrdersReset != null) btnOrdersReset.Enabled = !loading;
                if (btnOrdersFirst != null) btnOrdersFirst.Enabled = !loading;
                if (btnOrdersPrev != null) btnOrdersPrev.Enabled = !loading;
                if (btnOrdersNext != null) btnOrdersNext.Enabled = !loading;
                if (btnOrdersLast != null) btnOrdersLast.Enabled = !loading;
                if (cboOrdersPageSize != null) cboOrdersPageSize.Enabled = !loading;
                if (txtOrdersCode != null) txtOrdersCode.Enabled = !loading;
                if (txtOrdersName != null) txtOrdersName.Enabled = !loading;
                if (txtOrdersProductName != null) txtOrdersProductName.Enabled = !loading;
                if (cboOrdersState != null) cboOrdersState.Enabled = !loading;
            }
            
            // 更新窗体标题显示加载状态
            if (loading)
            {
                this.Text = "生产工单管理系统 - 加载中...";
            }
            else
            {
                this.Text = "生产工单管理系统";
            }
        }

        private async Task LoadProcessesAsync(CancellationToken cancellationToken = default(CancellationToken))
        {
            if (isLoading) return;
            isLoading = true;
            UpdateLoadingState(true);
            
            try
            {
                using (var httpClient = new HttpClient())
                {
                    httpClient.Timeout = TimeSpan.FromSeconds(15);
                    httpClient.DefaultRequestHeaders.Accept.Clear();
                    httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                    var requestUrl = "http://localhost:5257/api/ProductionOrders/ProcessTableCommand";
                    var response = await httpClient.GetAsync(requestUrl, cancellationToken).ConfigureAwait(false);
                    response.EnsureSuccessStatusCode();

                    var json = await response.Content.ReadAsStringAsync();

                    var apiEnvelope = JsonConvert.DeserializeObject<SimpleApiResponse<List<ProcessTable>>>(json);
                    var items = apiEnvelope?.data ?? new List<ProcessTable>();

                    Invoke(new Action(() =>
                    {
                        // 清空文本框
                        rtbProcess.Clear();
                        
                        if (items.Count == 0)
                        {
                            rtbProcess.AppendText("暂无工序数据");
                            return;
                        }
                        
                        // 添加标题
                        rtbProcess.SelectionFont = new Font("Microsoft YaHei", 14, FontStyle.Bold);
                        rtbProcess.SelectionColor = Color.DarkBlue;
                        rtbProcess.AppendText("📋 工序信息列表\n");
                        rtbProcess.SelectionFont = new Font("Microsoft YaHei", 10, FontStyle.Regular);
                        rtbProcess.SelectionColor = Color.Gray;
                        rtbProcess.AppendText("=".PadRight(60, '=') + "\n\n");
                        
                        // 设置表头样式
                        rtbProcess.SelectionFont = new Font("Consolas", 10, FontStyle.Bold);
                        rtbProcess.SelectionColor = Color.Black;
                        
                        // 添加表头
                        string header = string.Format("{0,-8} {1,-12} {2,-15} {3,-8} {4,-20} {5,-20}\n",
                            "🔢 工序ID", "📝 工序编号", "🏭 工序名称", "📊 状态", "📄 工序说明", "💬 备注");
                        rtbProcess.AppendText(header);
                        rtbProcess.SelectionColor = Color.DarkGray;
                        rtbProcess.AppendText("─".PadRight(120, '─') + "\n");
                        
                        // 设置数据样式
                        rtbProcess.SelectionFont = new Font("Consolas", 9, FontStyle.Regular);
                        
                        // 添加数据行
                        foreach (var item in items)
                        {
                            AppendProcessRow(rtbProcess, item);
                        }
                        
                        // 添加统计信息
                        rtbProcess.AppendText("\n" + "─".PadRight(120, '─') + "\n");
                        rtbProcess.SelectionFont = new Font("Microsoft YaHei", 9, FontStyle.Italic);
                        rtbProcess.SelectionColor = Color.Gray;
                        rtbProcess.AppendText($"📊 共 {items.Count} 条工序记录\n");
                        rtbProcess.AppendText($"🕒 更新时间: {DateTime.Now:yyyy-MM-dd HH:mm:ss}");
                    }));
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载工序失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                isLoading = false;
                UpdateLoadingState(false);
            }
        }

        private async Task LoadReportsAsync(CancellationToken cancellationToken = default(CancellationToken))
        {
            if (isLoading) return;
            isLoading = true;
            UpdateLoadingState(true);
            
            try
            {
                using (var httpClient = new HttpClient())
                {
                    httpClient.Timeout = TimeSpan.FromSeconds(15);
                    httpClient.DefaultRequestHeaders.Accept.Clear();
                    httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                    var requestUrl = $"http://localhost:5257/api/Report/ReportCommand?PageIndex={currentPageIndex}&PageSize={pageSize}";
                    
                    // 根据Swagger API文档，使用正确的筛选参数名称
                    if (!string.IsNullOrEmpty(filterDispatchCode))
                    {
                        requestUrl += $"&DispatchCode={Uri.EscapeDataString(filterDispatchCode)}";
                    }
                    if (!string.IsNullOrEmpty(filterDispatchName))
                    {
                        requestUrl += $"&DispatchName={Uri.EscapeDataString(filterDispatchName)}";
                    }
                    if (!string.IsNullOrEmpty(filterProductionOrdersCode))
                    {
                        requestUrl += $"&ProductionOrdersCode={Uri.EscapeDataString(filterProductionOrdersCode)}";
                    }
                    if (!string.IsNullOrEmpty(filterProductionOrdersName))
                    {
                        requestUrl += $"&ProductionOrdersName={Uri.EscapeDataString(filterProductionOrdersName)}";
                    }
                    if (!string.IsNullOrEmpty(filterReportingStaff))
                    {
                        requestUrl += $"&ReportingStaff={Uri.EscapeDataString(filterReportingStaff)}";
                    }
                    if (!string.IsNullOrEmpty(filterState))
                    {
                        requestUrl += $"&State={Uri.EscapeDataString(filterState)}";
                    }
                    
                    // 添加调试信息
                    var apiStateDisplay = GetStateDisplayText(filterState);
                    Console.WriteLine($"请求URL: {requestUrl}");
                    Console.WriteLine($"当前页: {currentPageIndex}, 页大小: {pageSize}");
                    Console.WriteLine($"筛选条件: 派工编号='{filterDispatchCode}', 派工名称='{filterDispatchName}', 工单编号='{filterProductionOrdersCode}', 工单名称='{filterProductionOrdersName}', 报工人员='{filterReportingStaff}', 状态='{apiStateDisplay}'");
                    Console.WriteLine($"筛选条件长度: 派工编号={filterDispatchCode?.Length ?? 0}, 派工名称={filterDispatchName?.Length ?? 0}, 工单编号={filterProductionOrdersCode?.Length ?? 0}, 工单名称={filterProductionOrdersName?.Length ?? 0}, 报工人员={filterReportingStaff?.Length ?? 0}, 状态={filterState?.Length ?? 0}");
                    var response = await httpClient.GetAsync(requestUrl, cancellationToken).ConfigureAwait(false);
                    response.EnsureSuccessStatusCode();

                    var json = await response.Content.ReadAsStringAsync();
                    Console.WriteLine($"API响应JSON: {json}");

                    var apiResponse = JsonConvert.DeserializeObject<ReportApiResponse>(json);
                    
                    if (apiResponse != null && apiResponse.code == 200)
                    {
                        var reportData = apiResponse.data;
                        // 根据Swagger API文档，使用pageDatas字段
                        var items = reportData?.pageDatas ?? new List<ReportTable>();
                        totalCount = reportData?.totalCount ?? 0;
                        totalPage = reportData?.totalPage ?? 0;
                    
                    // 添加调试信息
                        Console.WriteLine($"API响应成功: 总数={totalCount}, 总页数={totalPage}, 当前页数据条数={items.Count}");

                        // 更新分页信息显示
                        UpdatePagingInfo();



                    Invoke(new Action(() =>
                        {
                            dgvReport.DataSource = items;
                            
                            // 设置DataGridView的自动调整模式
                            dgvReport.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None;
                            dgvReport.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
                            
                            // 设置交替行颜色
                            dgvReport.AlternatingRowsDefaultCellStyle.BackColor = Color.LightGray;
                            dgvReport.DefaultCellStyle.SelectionBackColor = Color.LightBlue;
                            dgvReport.DefaultCellStyle.SelectionForeColor = Color.Black;
                            
                            if (dgvReport.Columns.Count > 0)
                            {
                                // 设置列标题
                                dgvReport.Columns[nameof(ReportTable.ReportId)].HeaderText = "报工主键";
                                dgvReport.Columns[nameof(ReportTable.DispatchCode)].HeaderText = "派工编号";
                                dgvReport.Columns[nameof(ReportTable.DispatchName)].HeaderText = "派工名称";
                                dgvReport.Columns[nameof(ReportTable.ProductionOrdersCode)].HeaderText = "工单编号";
                                dgvReport.Columns[nameof(ReportTable.ProductionOrdersName)].HeaderText = "工单名称";
                                dgvReport.Columns[nameof(ReportTable.SiteName)].HeaderText = "站点名称";
                                dgvReport.Columns[nameof(ReportTable.CraftName)].HeaderText = "工艺流程";
                                dgvReport.Columns[nameof(ReportTable.ProcessName)].HeaderText = "工序名称";
                                dgvReport.Columns[nameof(ReportTable.ProcessCode)].HeaderText = "工序编号";
                                dgvReport.Columns[nameof(ReportTable.TeamName)].HeaderText = "班组名称";
                                dgvReport.Columns[nameof(ReportTable.Leader)].HeaderText = "任务负责人";
                                dgvReport.Columns[nameof(ReportTable.ReportingStaff)].HeaderText = "报工人员";
                                dgvReport.Columns[nameof(ReportTable.ReportingNumber)].HeaderText = "报工数量";
                                dgvReport.Columns[nameof(ReportTable.ReportingTime)].HeaderText = "报工时间";
                                dgvReport.Columns[nameof(ReportTable.QualityInspectionTime)].HeaderText = "质检时间";
                                dgvReport.Columns[nameof(ReportTable.Qualified)].HeaderText = "合格";
                                dgvReport.Columns[nameof(ReportTable.NotQualified)].HeaderText = "不合格";
                                dgvReport.Columns[nameof(ReportTable.Rate)].HeaderText = "合格率";
                                dgvReport.Columns[nameof(ReportTable.State)].HeaderText = "状态";

                                // 设置列宽
                                dgvReport.Columns[nameof(ReportTable.ReportId)].Width = 80;
                                dgvReport.Columns[nameof(ReportTable.DispatchCode)].Width = 120;
                                dgvReport.Columns[nameof(ReportTable.DispatchName)].Width = 120;
                                dgvReport.Columns[nameof(ReportTable.ProductionOrdersCode)].Width = 120;
                                dgvReport.Columns[nameof(ReportTable.ProductionOrdersName)].Width = 120;
                                dgvReport.Columns[nameof(ReportTable.SiteName)].Width = 100;
                                dgvReport.Columns[nameof(ReportTable.CraftName)].Width = 100;
                                dgvReport.Columns[nameof(ReportTable.ProcessName)].Width = 100;
                                dgvReport.Columns[nameof(ReportTable.ProcessCode)].Width = 120;
                                dgvReport.Columns[nameof(ReportTable.TeamName)].Width = 100;
                                dgvReport.Columns[nameof(ReportTable.Leader)].Width = 100;
                                dgvReport.Columns[nameof(ReportTable.ReportingStaff)].Width = 100;
                                dgvReport.Columns[nameof(ReportTable.ReportingNumber)].Width = 80;
                                dgvReport.Columns[nameof(ReportTable.ReportingTime)].Width = 150;
                                dgvReport.Columns[nameof(ReportTable.QualityInspectionTime)].Width = 150;
                                dgvReport.Columns[nameof(ReportTable.Qualified)].Width = 60;
                                dgvReport.Columns[nameof(ReportTable.NotQualified)].Width = 60;
                                dgvReport.Columns[nameof(ReportTable.Rate)].Width = 80;
                                dgvReport.Columns[nameof(ReportTable.State)].Width = 80;

                                // 隐藏审计字段（创建人、创建时间等）
                                if (dgvReport.Columns.Contains("CreateBy"))
                                    dgvReport.Columns["CreateBy"].Visible = false;
                                if (dgvReport.Columns.Contains("CreateTime"))
                                    dgvReport.Columns["CreateTime"].Visible = false;
                                if (dgvReport.Columns.Contains("UpdBy"))
                                    dgvReport.Columns["UpdBy"].Visible = false;
                                if (dgvReport.Columns.Contains("UpdTime"))
                                    dgvReport.Columns["UpdTime"].Visible = false;
                                if (dgvReport.Columns.Contains("IsDel"))
                                    dgvReport.Columns["IsDel"].Visible = false;

                                // 设置时间列格式
                                dgvReport.Columns[nameof(ReportTable.ReportingTime)].DefaultCellStyle.Format = "yyyy-MM-dd HH:mm:ss";
                                dgvReport.Columns[nameof(ReportTable.QualityInspectionTime)].DefaultCellStyle.Format = "yyyy-MM-dd HH:mm:ss";

                                // 设置数字列格式
                                dgvReport.Columns[nameof(ReportTable.ReportingNumber)].DefaultCellStyle.Format = "N0";
                                dgvReport.Columns[nameof(ReportTable.Qualified)].DefaultCellStyle.Format = "N0";
                                dgvReport.Columns[nameof(ReportTable.NotQualified)].DefaultCellStyle.Format = "N0";
                                
                                // 设置合格率列格式 - 直接加%符号
                                dgvReport.Columns[nameof(ReportTable.Rate)].DefaultCellStyle.Format = "0%";
                                
                                // 设置状态列格式 - 将数字转换为文本显示
                                dgvReport.Columns[nameof(ReportTable.State)].DefaultCellStyle.Format = "0";
                                dgvReport.CellFormatting += DgvReport_CellFormatting;
                            }
                        }));
                    }
                    else
                    {
                        var errorMessage = apiResponse?.message ?? "未知错误";
                        if (apiResponse?.code != 200)
                        {
                            MessageBox.Show($"加载报工失败: {errorMessage}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载报工失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                isLoading = false;
                UpdateLoadingState(false);
            }
        }

        private string GetOrdersStateFilterValue()
        {
            if (cboOrdersState == null || cboOrdersState.SelectedIndex <= 0) return "";
            switch (cboOrdersState.SelectedIndex)
            {
                case 1: return "0"; // 待排产
                case 2: return "1"; // 未开始
                case 3: return "2"; // 进行中
                case 4: return "3"; // 已完成
                case 5: return "4"; // 已暂停
                case 6: return "5"; // 已关闭
            }
            return "";
        }

        private async Task LoadProductionOrdersAsync(CancellationToken cancellationToken = default(CancellationToken))
        {
            if (isLoading) return;
            isLoading = true;
            UpdateLoadingState(true);

            try
            {
                using (var httpClient = new HttpClient())
                {
                    httpClient.Timeout = TimeSpan.FromSeconds(15);
                    httpClient.DefaultRequestHeaders.Accept.Clear();
                    httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                    var requestUrl = $"http://localhost:5257/api/ProductionOrders/ProductionOrdersCommand?PageIndex={currentPageIndex}&PageSize={pageSize}";
                    if (!string.IsNullOrEmpty(ordersFilterCode)) requestUrl += $"&ProductionOrdersCode={Uri.EscapeDataString(ordersFilterCode)}";
                    if (!string.IsNullOrEmpty(ordersFilterName)) requestUrl += $"&ProductionOrdersName={Uri.EscapeDataString(ordersFilterName)}";
                    if (!string.IsNullOrEmpty(ordersFilterProductName)) requestUrl += $"&ProductName={Uri.EscapeDataString(ordersFilterProductName)}";
                    if (!string.IsNullOrEmpty(ordersFilterState)) requestUrl += $"&State={Uri.EscapeDataString(ordersFilterState)}";
                    var response = await httpClient.GetAsync(requestUrl, cancellationToken).ConfigureAwait(false);
                    response.EnsureSuccessStatusCode();

                    var json = await response.Content.ReadAsStringAsync();
                    Console.WriteLine($"ProductionOrders JSON: {json}");
                    var apiEnvelope = JsonConvert.DeserializeObject<ProductionOrdersApiResponse>(json);

                    var data = apiEnvelope?.data;
                    var items = data?.pageDatas ?? data?.data ?? new List<ProductionOrders>();
                    // 尝试补齐计划编号等可能命名不一致的字段
                    try
                    {
                        if ((items?.Count ?? 0) > 0)
                        {
                            var root = JObject.Parse(json);
                            var arr = (root["data"]["pageDatas"] ?? root["data"]["data"]) as JArray;
                            if (arr != null)
                            {
                                for (int i = 0; i < items.Count && i < arr.Count; i++)
                                {
                                    var t = arr[i];
                                    string planNo = (string)(t["planNumber"] ?? t["planNo"] ?? t["planCode"] ?? t["PlanNumber"] ?? t["PlanNo"] ?? t["PlanCode"]);
                                    if (!string.IsNullOrWhiteSpace(planNo))
                                    {
                                        items[i].PlanNumber = planNo;
                                    }
                                }
                            }
                        }
                    }
                    catch { /* 忽略补齐过程中的容错异常 */ }
                    totalCount = data?.totalCount ?? (items?.Count ?? 0);
                    totalPage = data?.totalPage ?? (totalCount > 0 ? (int)Math.Ceiling(totalCount / (double)pageSize) : 0);

                    Invoke(new Action(() =>
                    {
                        ShowOrdersPanel();
                        dgvOrders.DataSource = items;
                        dgvOrders.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None;
                        dgvOrders.AlternatingRowsDefaultCellStyle.BackColor = Color.LightGray;
                        dgvOrders.DefaultCellStyle.SelectionBackColor = Color.LightBlue;
                        dgvOrders.DefaultCellStyle.SelectionForeColor = Color.Black;

                        LocalizeOrdersHeaders();
                        EnsureOrdersActionColumn();
                        
                        // 在操作列添加后，再调整其他列的宽度
                        dgvOrders.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
                        
                        // 调试信息：检查操作列是否正确显示
                        Console.WriteLine($"数据加载完成，总列数: {dgvOrders.Columns.Count}");
                        if (dgvOrders.Columns.Contains("colSchedule"))
                        {
                            var actionCol = dgvOrders.Columns["colSchedule"];
                            Console.WriteLine($"操作列信息: 名称={actionCol.Name}, 可见={actionCol.Visible}, 宽度={actionCol.Width}, 位置={actionCol.DisplayIndex}");
                        }
                        else
                        {
                            Console.WriteLine("警告：操作列不存在！");
                        }
                        
                        // 检查所有列的可见性
                        Console.WriteLine("所有列信息:");
                        for (int i = 0; i < dgvOrders.Columns.Count; i++)
                        {
                            var col = dgvOrders.Columns[i];
                            Console.WriteLine($"列{i}: {col.Name}, 可见={col.Visible}, 宽度={col.Width}, 位置={col.DisplayIndex}");
                        }

                        lblOrdersTotal.Text = $"共{totalCount}条";
                        lblOrdersPage.Text = $"第{currentPageIndex}页/共{totalPage}页";
                        UpdateOrdersPagingButtons();
                    }));
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载生产工单失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                isLoading = false;
                UpdateLoadingState(false);
            }
        }

        private void HideIfExists(DataGridView grid, string columnName)
        {
            if (grid.Columns.Contains(columnName)) grid.Columns[columnName].Visible = false;
        }

        private void UpdateOrdersPagingButtons()
        {
            bool hasData = totalCount > 0;
            bool canGoFirst = currentPageIndex > 1;
            bool canGoPrev = currentPageIndex > 1;
            bool canGoNext = hasData && currentPageIndex < totalPage;
            bool canGoLast = hasData && currentPageIndex < totalPage;
            if (btnOrdersFirst != null) btnOrdersFirst.Enabled = canGoFirst && !isLoading;
            if (btnOrdersPrev != null) btnOrdersPrev.Enabled = canGoPrev && !isLoading;
            if (btnOrdersNext != null) btnOrdersNext.Enabled = canGoNext && !isLoading;
            if (btnOrdersLast != null) btnOrdersLast.Enabled = canGoLast && !isLoading;
        }

        // 强制刷新工单表格显示
        private void RefreshOrdersDisplay()
        {
            if (dgvOrders != null)
            {
                dgvOrders.Refresh();
                // 重新绑定数据源以触发格式化事件
                var currentDataSource = dgvOrders.DataSource;
                dgvOrders.DataSource = null;
                dgvOrders.DataSource = currentDataSource;
                
                // 确保操作列正确显示
                EnsureOrdersActionColumn();
                
                // 强制刷新操作列的显示
                if (dgvOrders.Columns.Contains("colSchedule"))
                {
                    dgvOrders.Columns["colSchedule"].Visible = true;
                    dgvOrders.Columns["colSchedule"].Width = 80;
                    dgvOrders.Invalidate(); // 强制重绘
                }
            }
        }

        private void EnsureOrdersActionColumn()
        {
            if (dgvOrders == null) return;
            const string columnName = "colSchedule";
            if (!dgvOrders.Columns.Contains(columnName))
            {
                var col = new DataGridViewButtonColumn
                {
                    Name = columnName,
                    HeaderText = "操作",
                    Text = "排产",
                    UseColumnTextForButtonValue = true, // 改回true，确保按钮文本能正常显示
                    Width = 80, // 增加列宽，确保按钮完整显示
                    AutoSizeMode = DataGridViewAutoSizeColumnMode.None,
                    FlatStyle = FlatStyle.Flat, // 设置按钮样式
                    Resizable = DataGridViewTriState.False // 禁止调整列宽
                };
                dgvOrders.Columns.Add(col);
                dgvOrders.CellContentClick += DgvOrders_CellContentClick;
                dgvOrders.CellFormatting += DgvOrdersAction_CellFormatting; // 添加操作列的格式化事件
                
                Console.WriteLine($"操作列已添加: {columnName}, 列数: {dgvOrders.Columns.Count}");
            }
            else
            {
                Console.WriteLine($"操作列已存在: {columnName}");
                // 确保现有操作列可见
                var existingCol = dgvOrders.Columns[columnName];
                existingCol.Visible = true;
                existingCol.Width = 80;
            }
        }

        private void DgvOrders_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0 || e.ColumnIndex < 0) return;
            var grid = sender as DataGridView;
            if (grid.Columns[e.ColumnIndex].Name == "colSchedule")
            {
                if (grid.Rows[e.RowIndex].DataBoundItem is ProductionOrders current)
                {
                    if (current.State == 0)
                    {
                        // 待排产状态：打开排产窗体
                        using (var dlg = new ScheduleForm(current))
                        {
                            if (dlg.ShowDialog(this) == DialogResult.OK)
                            {
                                // 排产成功后，立即刷新数据以显示状态变化
                                _ = LoadProductionOrdersAsync();
                                // 强制刷新当前行的显示
                                RefreshOrdersDisplay();
                            }
                        }
                    }
                    else
                    {
                        // 其他状态：打开只读查看窗体
                        using (var dlg = new ScheduleForm(current, true)) // 传入只读参数
                        {
                            dlg.ShowDialog(this);
                        }
                    }
                }
            }
        }

        private void LocalizeOrdersHeaders()
        {
            if (dgvOrders == null || dgvOrders.Columns.Count == 0) return;
            void SetHeader(string name, string text)
            {
                if (dgvOrders.Columns.Contains(name)) dgvOrders.Columns[name].HeaderText = text;
            }

            SetHeader(nameof(ProductionOrders.ProductionOrdersId), "工单主键");
            SetHeader(nameof(ProductionOrders.ProductionOrdersCode), "工单编号");
            SetHeader(nameof(ProductionOrders.ProductionOrdersName), "工单名称");
            SetHeader(nameof(ProductionOrders.ProductionOrdersProgress), "工单进度");
            SetHeader(nameof(ProductionOrders.AssociatePlans), "关联计划");
            SetHeader(nameof(ProductionOrders.PlanNumber), "计划编号");
            SetHeader(nameof(ProductionOrders.Type), "类型");
            SetHeader(nameof(ProductionOrders.ProductName), "产品名称");
            SetHeader(nameof(ProductionOrders.ProductCode), "产品编号");
            SetHeader(nameof(ProductionOrders.SpecificationModel), "规格型号");
            SetHeader(nameof(ProductionOrders.ProductType), "产品类型");
            SetHeader(nameof(ProductionOrders.Unit), "单位");
            SetHeader(nameof(ProductionOrders.BOM), "BOM");
            SetHeader(nameof(ProductionOrders.Version), "版本");
            SetHeader(nameof(ProductionOrders.PlannedQuantity), "计划数量");
            SetHeader(nameof(ProductionOrders.ActualQuantity), "实际数量");
            SetHeader(nameof(ProductionOrders.PlanStart), "计划开工");
            SetHeader(nameof(ProductionOrders.PlanEnd), "计划完工");
            SetHeader(nameof(ProductionOrders.ActualStart), "实际开工");
            SetHeader(nameof(ProductionOrders.ActualEnd), "实际完工");
            SetHeader(nameof(ProductionOrders.Batch), "生产批次");
            SetHeader(nameof(ProductionOrders.DemandDate), "需求日期");
            SetHeader(nameof(ProductionOrders.Remark), "备注");

            if (dgvOrders.Columns.Contains(nameof(ProductionOrders.State)))
            {
                dgvOrders.Columns[nameof(ProductionOrders.State)].HeaderText = "状态";
                dgvOrders.CellFormatting -= DgvOrders_CellFormatting;
                dgvOrders.CellFormatting += DgvOrders_CellFormatting;
            }

            // 确保操作列可见且位置正确
            if (dgvOrders.Columns.Contains("colSchedule"))
            {
                dgvOrders.Columns["colSchedule"].Visible = true;
                dgvOrders.Columns["colSchedule"].DisplayIndex = dgvOrders.Columns.Count - 1; // 放在最后一列
            }

            // 隐藏审计字段
            HideIfExists(dgvOrders, "CreateBy");
            HideIfExists(dgvOrders, "CreateTime");
            HideIfExists(dgvOrders, "UpdBy");
            HideIfExists(dgvOrders, "UpdTime");
            HideIfExists(dgvOrders, "IsDel");
        }
    }
}
